package com.myservlet01;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Servlet04_Cookie_Session
 */
public class Servlet04_Cookie_Session extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Servlet04_Cookie_Session() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	//	response.getWriter().append("Served at: ").append(request.getContextPath());
	
	   response.setHeader("content-type", "text/html;charset=utf-8"); 
	   PrintWriter out=response.getWriter();
	   Cookie[] cookies= request.getCookies();

	   for(int i=0; cookies!=null&& i<cookies.length;i++) {
		  if("lastAccessTime".equals(cookies[i].getName())) {
			  long l= Long.parseLong(cookies[i].getValue());
			  out.write("你的最后访问时间:"+new Date(l).toLocaleString());//yyyy-MM-dd
		  }
	   }
	   //创建cookie存储第一个访问内容
	   // name 
	   // value : 不能存中文
	   // mMaxAge: cookie存储时间，默认-1，浏览器关闭，没了
	   Cookie ck= new Cookie("lastAccessTime", System.currentTimeMillis()+"");
	   //浏览器关闭cookie还在解决
	   // 0删除cookie
	   ck.setMaxAge(60*5);  //5分钟
	   
	   // http://localhost:8080/03_servlet2_5/*
	   // 当前应用下所有servlet 都可以访问
	   
	   ck.setPath("/");
	   response.addCookie(ck);
	   
	
	   //删除cookie
	   out.print("<a href='"+request.getContextPath()+"/Servlet03'>clear</a>");
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
